import {getAntd, getEcCom} from '../../util/convert';
import {inject, observer} from "mobx-react/index";
import {toJS} from 'mobx';
import * as _ from '../../util/public/common';
import "../../style/free.less";
import {Button} from "antd";
import FreeImportModalCom from './FreeImportModalCom';
import * as type from '../../constants/type';
import React from "react";

@inject('globalStore', 'freeWorkflowNewStore')
@observer
export default class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ""
    };
  }
  componentWillMount() {

    const { getNodeList} = this.props.freeWorkflowNewStore;
    getNodeList();
  }
  componentDidMount(){
    let openPage = sessionStorage.getItem("openFreeBrowser");
    let _that = this;
    if(openPage && openPage=="1"){
      let timer = setInterval(function () {
        if(_that.browser && _that.browser.openModal){
          clearInterval(timer);
          _that.browser.openModal();
        }
      },500)
      sessionStorage.removeItem("openFreeBrowser");
    }
  }
  getFreeCom=(freeNodeDatas={},comp=[],addNodePosition=0)=>{
    let {Popover} = getAntd();
    let {currentGroupId,currentnodeid,addNextNode,isEdit,FreeNodeList,setProperty,deleteNode,signType} = this.props.freeWorkflowNewStore;
    let {commonParam={},rightMenu={}} = WfForm.getGlobalStore();
    let {requestid = -1} = commonParam;
    if(!_.isEmpty(freeNodeDatas)){
      let {noOperatedUsers=[],nodeEntity={},id=-1,nodeid=-1,nodeChartEntity={},viewedUsers=[],operatedUsers=[]} = freeNodeDatas;
      let {operatorReplaceDatas=[],isxb=""} = nodeEntity;
      let {addNext=false,del=false,edit=false} = nodeChartEntity;
      let isCurrent = currentnodeid==nodeid;
      let name = this.getShowOperatorName((del && isEdit==1),noOperatedUsers,operatedUsers,operatorReplaceDatas);//operatorReplaceDatas.length>0?operatorReplaceDatas[0].name:"暂未设置操作者";
      let sign = ((isCurrent||operatedUsers.length==0)&&isxb!="1")?"1":"0";
      let child = (<div className={`rectangle ${isCurrent?"current":operatedUsers.length>0?"haveviewed":"notviewed"}`}>
        <div className="content-wrap">
          {del && isEdit==1 && <span className={"deleteNode"} onClick={()=>{
            setProperty({deleteNodePosition:addNodePosition,deleteids:id});
            deleteNode(operatorReplaceDatas);
          }}><i className="icon-coms-Loss" /></span>}
          <div className={"area left-area"}>
            <i className={`${isCurrent?"icon-coms02-coms-node":operatedUsers.length>0?"icon-coms-organization-right":(freeNodeDatas["next"] && !_.isEmpty(freeNodeDatas["next"]))?"icon-coms-organization-right":"icon-coms-Tile-o"}`}></i>
          </div>
          <div className="area right-area" onDoubleClick={()=>{
            this.doAddAndSub(nodeid,requestid,sign);
          }}>
            <div className="info-content"
                 style={{display:"inline-block"}}><span title={name}>{name}</span></div>
            {
              operatorReplaceDatas.length>1 && <div style={{display:"inline-block",verticalAlign:"text-bottom"}}>
                <i className="icon-coms-HumanResources" style={{fontSize:"17px",marginLeft:"10px",color:"rgb(0, 121, 222)"}}/>
              </div>
            }
          </div>
          {addNext&& isEdit==1 && <span className={"addNode"} onClick={()=>{
            setProperty({addNodePosition});
            event.preventDefault();
            event.stopPropagation();
            this.openBrowserModal(nodeid);
          }}><i className="icon-coms-plus" /></span>}
        </div>
      </div>);
      if(operatorReplaceDatas.length>1){
        let sign = ((isCurrent||operatedUsers.length==0)&&isxb!="1")?"1":"0";
        child = (<div className={`rectangle ${isCurrent?"current":operatedUsers.length>0?"haveviewed":"notviewed"}`}>
          <div className="content-wrap">
            {del && isEdit==1 && <span className={"deleteNode"} onClick={()=>{
              setProperty({deleteNodePosition:addNodePosition,deleteids:id});
              deleteNode(operatorReplaceDatas);
            }}><i className="icon-coms-Loss" /></span>}
            <Popover placement="bottom" title={"操作者"} content={this.getOperatorTip(viewedUsers,noOperatedUsers,operatedUsers,operatorReplaceDatas)} trigger="click" overlayClassName={"wf-req-freeWorkflowNew-operaters"}>
              <div style={{width:"100%",height:"100%"}}>
                <div className={"area left-area"}>
                  <i className={`${isCurrent?"icon-coms02-coms-node":operatedUsers.length>0?"icon-coms-organization-right":(freeNodeDatas["next"] && !_.isEmpty(freeNodeDatas["next"]))?"icon-coms-organization-right":"icon-coms-Tile-o"}`}></i>
                </div>
                <div className="area right-area" onDoubleClick={()=>{
                  this.doAddAndSub(nodeid,requestid,sign);
                }}>
                  <div className="info-content"  style={{display:"inline-block"}}><span title={name}>{name}</span></div>
                  {
                    operatorReplaceDatas.length>1 && <div style={{display:"inline-block",verticalAlign:"text-bottom"}}>
                      <i className="icon-coms-HumanResources" style={{fontSize:"17px",marginLeft:"10px",color:"rgb(0, 121, 222)"}}/>
                    </div>
                  }
                </div>
              </div>
            </Popover>
            {addNext&& isEdit==1 && <span className={"addNode"} onClick={()=>{
              setProperty({addNodePosition});
              event.preventDefault();
              event.stopPropagation();
              this.openBrowserModal(nodeid);
            }}><i className="icon-coms-plus" /></span>}
          </div>
        </div>);
      }
      comp.push(child);
      if(freeNodeDatas["next"]){
        return this.getFreeCom(freeNodeDatas["next"],comp,addNodePosition+1);
      }
    }
    return comp;
  }
  
  getShowOperatorName = (del,noOperatedUsers=[],operatedUsers=[],operatorReplaceDatas=[]) => {
        let name = this.getOperatorName(noOperatedUsers);

        if(!name && del == false){
            name = this.getOperatorName(operatedUsers);
        }
      if(!name){
          name = this.getOperatorName(operatorReplaceDatas);
      }
      if(!name){
          name = '暂未设置操作者';
      }
	  return name;
  }

  getOperatorName = (operatedUsers = []) => {
      if(operatedUsers && operatedUsers.length > 0){
          for(let idx = operatedUsers.length-1;idx > -1;idx --){
              if(operatedUsers[idx].intervene != 1){
                  return operatedUsers[idx].lastname || operatedUsers[idx].name;
              }
          }
      }
      return '';
  }
  
  getOperatorTip=(viewedUsers=[],noOperatedUsers=[],operatedUsers=[],operatorReplaceDatas=[])=>{
    if(operatedUsers.length<=0 && noOperatedUsers.length<=0){
      noOperatedUsers = operatorReplaceDatas;
    }
    return <div>
      {
        noOperatedUsers.length>0 && <div className={"nooperator"}>
          <div className={"head"}>未操作</div>
          <div className={"content"}>
            {noOperatedUsers.map(item=>{
                let name = item.lastname || item.name;
                name = name.replace("(协办)","")
                return <span>{name}</span>
            })}
          </div>
        </div>
      }
      {
        // viewedUsers.length>0 && <div className={"viewedoperator"}>
        //   <div className={"head"}>已查看</div>
        //   <div className={"content"}>
        //     {viewedUsers.map(item=>{
        //         let name = item.lastname || item.name;
        //         name = name.replace("(协办)","")
        //         return <span>{name}</span>
        //     })}
        //   </div>
        // </div>
      }
      {
        operatedUsers.length>0 && <div className={"haveoperator"}>
          <div className={"head"}>已操作</div>
          <div className={"content"}>
            {operatedUsers.map(item=>{
                let name = item.lastname || item.name;
                name = name.replace("(协办)","")
                return <span>{name}</span>
            })}
          </div>
        </div>
      }
    </div>
  }
  openBrowserModal = (oprateNodeId)=>{
    let {setProperty} = this.props.freeWorkflowNewStore;
    let {commonParam={},rightMenu={}} = WfForm.getGlobalStore();
    let {requestid = -1} = commonParam;
    if(requestid<1){
      sessionStorage.setItem("openFreeBrowser","1");
      WfForm.doRightBtnEvent("BTN_WFSAVE");
    }else {
      setProperty({signType:"2",oprateNodeId});
      this.browser.openModal();
    }
  }

  getImportModalCom=()=>{
    return <div style={{display:"none"}}>



    </div>
  }

    doAddAndSub=(nodeid,requestid,sign)=>{
        if(sign=="1"){
          const { invalidParam={},dialogVisible,controlDialogVisible } = this.props.globalStore;
          const {EnableProcessAdditionAndSubtraction='',EnableProcessIntervention=''} =invalidParam;
          let {signType,setProperty} = this.props.freeWorkflowNewStore;
          if(EnableProcessAdditionAndSubtraction&&EnableProcessAdditionAndSubtraction=="1"){
            setProperty({clicknodeid:nodeid});
            setProperty({clickrequestid:requestid});
            controlDialogVisible(type.EnableProcessAdditionAndSubtraction,true);
          }
        }

    }
    getdatdacom(){
      let {setProperty,xiebandata} = this.props.freeWorkflowNewStore;
      const { WeaDatePicker} = getEcCom();
      return(
        <span style={{float: "left",
        margin:"6px 0 0 20px" }} class="signdatapick">
        限时征询：
        <WeaDatePicker
        noInput
        value={xiebandata}
        viewAttr={2}
        onChange={value => setProperty({xiebandata : value})}
        />
      </span>
      );
    }
  render() {
    let {freeNodeDatas,createNodeDatas,addNextNode,signType,setProperty,isEdit,createNodeid,currentnodeid,allowAddNewBranch,
      showSaveModalDialog,modal,saveAsTempSave,getFlowTemplateList,loading,xiebandata} = this.props.freeWorkflowNewStore;
    let startClass = (currentnodeid>0 && currentnodeid==createNodeid)?"current":"haveviewed";
    let {WeaBrowser,WeaLocaleProvider,WeaSelect,WeaDialog,WeaFormItem,WeaInput} = getEcCom();
    let {name,type} =toJS(modal);
    const getLabel = WeaLocaleProvider.getLabel;
    const options = [
      {
        key: "2",
        showname: getLabel('533375','逐级处理')
      }, {
        key: "1",
        showname: getLabel('15557','会签') 
      }, {
            key: "7",//ylc
            showname: "意见征询" 
      }
    ];
    const optionsModal = [
      {
        key: "0",
        showname: getLabel('83159','个人模板') 
      }, {
        key: "1",
        showname: getLabel('533376','公用模板') 
      }
    ];
    const {Spin } = getAntd();
    if(loading){
      return <div id={"FreeWorkflowNewXXC"} className='wf-req-freeWorkflowNew' style={{width:"100%"}}>
        <div style={{margin:"10px auto"}}><Spin size="large" /></div>
      </div>
    }
    let datacom=signType==7?this.getdatdacom():"";
    let moudle=[
      
        <WeaSelect
            className={"signselect"}
            style={{float: "left",
              margin:"6px 0 0 20px"
            }}
            options={options}
            detailtype={3}
            value={signType}
            onChange={v=>{
            setProperty({signType : v})
            }}
        />
        ,
        datacom,

    ];
    return (
        <div id={"FreeWorkflowNewXXC"} className='wf-req-freeWorkflowNew' style={{width:"100%"}}>
          <div id="smartGuessPicBoxNew" style={{height:"100%",width:`${currentnodeid==createNodeid?"calc(100% - 150px)":"100%"}`}}>
            <div  className={"outer-wrap-box wrap-box-flex-left notFromMobile"}>

              {
                toJS(createNodeDatas).map(item=>{
                  let {id="",name="",isCurrent=false,haveviewed=false,notviewed=false} = item;
                  return <div className={`rectangle ${startClass}`}>
                    <div className="content-wrap">
                      <div className={"area left-area"}>
                        <i className="icon-coms-organization-right"></i>
                      </div>
                      <div className="area right-area">
                        <div className="info-content"><span title="系统管理员">{name}</span></div>
                      </div>
                      {allowAddNewBranch && isEdit==1&& <span className={"addNode"} onClick={()=>{
                        this.openBrowserModal(-1);
                        setProperty({addNodePosition:-1});
                      }}><i className="icon-coms-plus" /></span>}
                    </div>
                  </div>
                })
              }
              {
                this.getFreeCom(toJS(freeNodeDatas),[],0)
              }
              <div style={{display:"none"}}>
                <WeaBrowser
                    ref={ref=>this.browser = ref}
                    type={17}
                    textDecoration={true}
                    inputStyle={{ width: 200 }}
                    onChange={(ids, names, datas) =>{
                      setProperty({selectedPersons:{ids, names, datas}});
                      addNextNode();
                    }
                    }
                    _noOverwrite
                    customized
                    isSingle={false}
                    getRenderModule={(context, modules) => {
                      const { isSingle, browserModalProps } = context.props;
                      const { contentType, selectedData } = context.state;
                      const disabled = selectedData.length === 0;
                      let arr=[
                        <Button
                        key="submit"
                        type="primary"
                        disabled={disabled}
                        onClick={context.handleOk}
                    >
                      {[
                        getLabel(385565, '确 定'),
                        isSingle || disabled ? '' : context.count(selectedData),
                      ]}
                    </Button>,
                    <Button  key="back" type="ghost" onClick={context.handleCancel}>
                      {getLabel(385567, '取 消')}
                    </Button>,
                      ];
                      let array=moudle.concat(arr);
                      return {
                        module_3_1: array,
                      };
                    }}
                />
              </div>
            </div>
          </div>
          <div style={{display:`${currentnodeid==createNodeid?"inline-block":"none"}`,width:"148px",float:"right",height:"100%",textAlign:"center",borderLeft:"1px solid #eee"}}>
            <div style={{padding:"12px 0 5px 0"}}>
              <Button type={"primary"} onClick={()=>{
setProperty({showSaveModalDialog:true})
}}>{getLabel('18418','存为模板')}</Button>
            </div>
            <div style={{padding:"5px 0"}}>
              <Button type={"primary"} onClick={()=>{
setProperty({showImportModalDialog:true});getFlowTemplateList();
}}>{getLabel('129833','导入模板')}</Button>
            </div>
          </div>
          <WeaDialog
              title={getLabel('18418','存为模板')}
              style={{width:500,height:180}}
              visible={showSaveModalDialog}
              iconBgcolor={"rgb(0, 121, 222)"}
              icon={"icon-coms-workflow"}
              buttons={[
                  <Button type={"primary"} onClick={saveAsTempSave}>保存</Button>
              ]}
              onCancel={() =>{
                setProperty({showSaveModalDialog:false})
              } }
          >
            <div style={{padding:"40px 40px"}}>
              <WeaFormItem
                  label="模板名称"
                  labelCol={{span: 8}}
                  wrapperCol={{span: 16}}
                  style={{marginBottom:"20px"}}
              >
                <WeaInput value={name} viewAttr={3} onChange={(v)=>{
                  setProperty({modal:{name:v,type}})
                }}/>
              </WeaFormItem>
              <WeaFormItem
                  label="类型"
                  labelCol={{span: 8}}
                  wrapperCol={{span: 16}}
              >
                <WeaSelect
                    options={optionsModal}
                    value={type}
                    onChange={v=>{
setProperty({modal:{type:v,name}})
}}
                />
              </WeaFormItem>
            </div>
          </WeaDialog>
          <FreeImportModalCom/>
        </div>
    )
  }

}